#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include <thread>


//5.全局变量在线程内部是共享的
int gval = 100;

std::string toHex(pthread_t tid)
{
    //4.进程内的函数,线程共享
    char buffer[64];
    snprintf(buffer,sizeof(buffer),"0x%lx",tid);
    return buffer;
}

void* routine1(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        //3.不加保护的情况下,显示器文件就是共享资源
        std::cout << "我们是新线程,我的名字是: " << name << 
        ", my tid is : " << toHex(pthread_self()) 
        << ", 全局变量(修改): " << gval<< std::endl;
        gval++;
        sleep(1);
    }
    return 0;
}

void* routine2(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        //3.不加保护的情况下,显示器文件就是共享资源
        std::cout << "我们是新线程,我的名字是: " << name << 
        ", my tid is : " << toHex(pthread_self()) 
        << ", 全局变量(只是检测): " << gval<< std::endl;
        sleep(1);
        //6.线程一旦出现异常,可能会导致其他线程全部奔溃
        int *p = nullptr;
        *p = 100;
    }
    return 0;
}

int main()
{
    //1.新线程和main线程谁先运行,不确定
    //2.新线程创建出来,要对进程的时间片进行瓜分
    pthread_t tid1;
    pthread_create(&tid1,nullptr,routine1,(void*)"thread-1");
    pthread_t tid2;
    pthread_create(&tid2,nullptr,routine2,(void*)"thread-2");
    
    printf("new thread id: 0x%lx\n",tid1);
    printf("new thread id: 0x%lx\n",tid2);

    while(true)
    {
        std::cout << "我们是main线程..." << " , my tid is : " << toHex(pthread_self()) << std::endl;
        sleep(1);
    }
    return 0;
}



